package cn.jdemo.juc.thread.daemon;

import java.util.concurrent.TimeUnit;

/**
 *
 * (1) thread.setDaemon(true)必须在thread.start()之前设置，否则会抛出异常；
 * (2) 在Daemon线程中产生的新线程也是Daemon的；
 * (3) 守护线程应该永远不去访问固有资源，如文件、数据库，因为它会在任何时候甚至在一个操作的中间发生中断；
 *
 * @description
 * @date 2020/12/21
 */
public class Demo01 {
    public static void main(String[] args) throws InterruptedException {
        test01();
        test02();
    }

    /**
     * 仅有守护线程，则主线程断，守护线程断
     * @throws InterruptedException
     */
    public static void test01() throws InterruptedException {
        Thread thread01 = new Thread(() -> {
            try {
                while (true){
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("start 001");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread01.setDaemon(true);
        thread01.start();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("main over");
    }

    /**
     * 既有守护线程也有非守护线程,主线程断,二者都没断
     * @throws InterruptedException
     */
    public static void test02() throws InterruptedException {
        Thread thread01 = new Thread(() -> {
            try {
                while (true){
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("start 01");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread01.setDaemon(true);
        thread01.start();

        Thread thread02 = new Thread(() -> {
            try {
                while (true){
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("start 02");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread02.setDaemon(false);
        thread02.start();

        TimeUnit.SECONDS.sleep(3);
        System.out.println("main over");
    }

}
